package com.xiao.singleapp.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JDBC 操作数据库执行器封装
 * 代码生成器只需要封装查询操作即可
 *
 * @CreateBy 花和尚  1130365579@qq.com  2023/3/20 1:20
 * @Version 1.0
 */
public class JdbcTemplate {

    public static void main(String[] args) throws SQLException {
        System.out.println(queryResultToListMap("SELECT DATABASE()"));
    }

    /**
     * 查询语句执行
     *
     * @param params 查询参数
     * @return
     */
    public static List<Map<String, String>> queryResultToListMap(String querySql, Object... params) throws SQLException {
        Connection conn = null;
        PreparedStatement preStat = null;
        ResultSet resultSet = null;
        List<Map<String, String>> result = null;
        try {
            conn = JdbcUtil.getConn();
            conn.setAutoCommit(false);
            preStat = conn.prepareStatement(querySql);
            preStat.execute();
            conn.commit();
            resultSet = preStat.getResultSet();
            result = toListMap(resultSet);
        } catch (Exception e) {
            assert conn != null;
            conn.rollback();
            e.printStackTrace();
        } finally {
            JdbcUtil.release(resultSet, preStat, conn);
        }
        return result;
    }

    /**
     * 封装成 List<Map<String, Object>> 结构
     *
     * @param resultSet 查询结果集
     * @return
     */
    private static List<Map<String, String>> toListMap(ResultSet resultSet) throws SQLException {
        List<Map<String, String>> resultList = new ArrayList<>();
        Map<String, String> rowMap;
        // 元数据
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (resultSet.next()) {
            // 5 是因为业务设定 预计都是4 或 5
            rowMap = new HashMap<>(5);
            metaData = resultSet.getMetaData();
            for (int i = 1; i <= columnCount; i++) {
                // 根据索引 获取 字段名和字段值
                rowMap.put(metaData.getColumnName(i), resultSet.getString(i));
            }
            resultList.add(rowMap);
        }
        return resultList;
    }
}
